package com.aos;

public class SpanTreeDeamon extends Thread
{
	public void run()
	{
		//System.out.println("Inside Deamon.");
		while(!Node.isSpanningCompleted())
		{
			try {
				Thread.sleep(3000);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
			//System.out.println("Not terminated....");
		}
		
		//System.out.println("Spanning Completed.");
		String spanTree = "";
		String specifiedDegreeNodes = "";
		//for offsetting root, it doesn't have parent
		int parentOffset = 0;
		if(Node.nodeInfo.getID() != Node.parent)
		{
			parentOffset = 1;
		}
		int minDegree = Node.childCount + parentOffset;
		int maxDegree = Node.childCount + parentOffset;
		
		for(Integer child : Node.children)
		{
			spanTree += "(" + Node.nodeInfo.getID() + " " + child + ")";			
		}
		if(Node.childCount + parentOffset <= Node.specifiedDegree)
		{
			specifiedDegreeNodes = Integer.toString(Node.nodeInfo.getID());
		}
		spanTree = spanTree.trim();
		Node.updateSpanTreeInfo(minDegree, maxDegree, spanTree, specifiedDegreeNodes);
		
		String msg = Node.nodeInfo.getID() + "~" + Node.minDegree + "~" + Node.maxDegree + "~" + Node.spanningTree + "~" + Node.specificDegreeNodes;
		if(Node.nodeInfo.getID() == Node.dNode)
		{
			/*
			System.out.println("Spanning Tree: "+ Node.spanningTree);
			System.out.println("Min Degree: "+ Node.minDegree);
			System.out.println("Max Degree: "+ Node.maxDegree);
			System.out.println(Node.specificDegreeNodes);
			*/			
			//for designated node start height computation process
			for(Integer child : Node.children)
			{
				Communication.sendMessage(Client.senderList.get(child), Communication.h_req_msg, Integer.toString(Node.nodeInfo.getID()), Integer.toString(child));
			}
						
		}else
		{
			//System.out.println("*A T message " + Node.minDegree + " " + Node.maxDegree + Node.spanningTree + " is sending to Node: " + Node.parent + "*");
			Communication.sendMessage(Client.senderList.get(Node.parent), Communication.t_msg, msg, Integer.toString(Node.parent));
		}		
	}
}
